package com.cskaoyan.controller;

import com.cskaoyan.bean.Admin;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.ListData;
import com.cskaoyan.service.AdminAdminService;
import com.fasterxml.jackson.databind.ser.Serializers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author heyyon
 * 系统管理-管理员
 */
@RestController
@RequestMapping("admin/admin")
public class AdminAdminController {
    @Autowired
    AdminAdminService adminAdminService;

    @RequiresPermissions(value = {"admin:admin:list"})
    @RequestMapping("list")
    public BaseRespVo list(Integer page, Integer limit, String username, String sort, String order) {
        ListData<Admin> admins = adminAdminService.list(page, limit, username, sort, order);
        return BaseRespVo.ok(admins);
    }

    @PostMapping("create")
    public BaseRespVo create(@RequestBody Admin admin, HttpServletRequest request) {
        String currentUsername = (String) request.getSession().getAttribute("name");
        Admin newlyCreatedAdmin = adminAdminService.create(admin, currentUsername);
        return BaseRespVo.ok(newlyCreatedAdmin);
    }

    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Admin admin, HttpServletRequest request) {
        String currentUsername = (String) request.getSession().getAttribute("name");
        int row = adminAdminService.delete(admin,currentUsername);
        if (row != 0) {
            return BaseRespVo.ok();
        }
        return BaseRespVo.fail();
    }

    @PostMapping("update")
    public BaseRespVo update(@RequestBody Admin admin, HttpServletRequest request) {
        String currentUsername = (String) request.getSession().getAttribute("name");
        Admin updatedAdmin = adminAdminService.update(admin, currentUsername);
        return BaseRespVo.ok(updatedAdmin);
    }
}
